package com.vids.task;

import lombok.RequiredArgsConstructor;

import java.io.File;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;

@RequiredArgsConstructor
public class RemoveFilesTask implements Runnable {

    private final  String root_dir;

    public void deleteDirectory(File directory) {
        if (directory.exists()) {
            File[] files = directory.listFiles();
            if (null != files) {
                for (File file : files) {
                    if (file.isDirectory()) {
                        deleteDirectory(file);
                    } else {
                        file.delete();
                    }
                }
            }
        }
        directory.delete();
    }

    @Override
    public void run() {
        LocalDate keep_date = LocalDate.now().minusDays(1);
        File f_root_dir = new  File(root_dir);
        File[]  root_files =  f_root_dir.listFiles();
        String date_dir_name;

        for (File f : root_files) {
            if (f.isDirectory())
            {
                date_dir_name = f.getName();
                LocalDate date_dir =  LocalDate.parse(date_dir_name, DateTimeFormatter.ofPattern("yyyy-MM-dd"));
                if (date_dir.isBefore(keep_date) || date_dir.isEqual(keep_date))
                {
                    deleteDirectory(f);
                }
            }
        }
    }
}
